<?php
class Calc_Task
{
    public function run()
    {
        $collections = Collection::getAll();

        print_r($this->getMaxLineByUserAndCollection(1, $collections[2]));
    }

    protected function getMaxLineByUserAndCollection($userId, $collection)
    {
        $results = User::results($userId);

        $maxLine = array(
            'f' => array(
                'start' => -1, # start line result ID
                'count' => 0
            ),
            'l' => array(
                'start' => -1,
                'count' => 0,
            )
        );

        $tracking = array(
            'f' => array(
                'start' => -1, # start line result ID
                'count' => 0,
                'inLine' => false
            ),
            'l' => array(
                'start' => -1,
                'count' => 0,
                'inLine' => false
            )
        );

        foreach ($results as $curResult)
        {
            if (in_array($curResult->first, $collection['numbers']))
            {
                if ($tracking['f']['inLine'])
                {
                    $tracking['f']['count']++;
                }
                else
                {
                    $tracking['f']['inLine'] = true;
                    $tracking['f']['start'] = $curResult->id;
                    $tracking['f']['count'] = 1;
                }
            }
            else
            {
                if ($tracking['f']['inLine'])
                {
                    $tracking['f']['inLine'] = false;
                    if ($maxLine['f']['count'] < $tracking['f']['count'])
                    {
                        $maxLine['f']['count'] = $tracking['f']['count'];
                        $maxLine['f']['start'] = $tracking['f']['start'];
                    }
                }
            }

            // Last
            if (in_array($curResult->last, $collection['numbers']))
            {
                if ($tracking['l']['inLine'])
                {
                    $tracking['l']['count']++;
                }
                else
                {
                    $tracking['l']['inLine'] = true;
                    $tracking['l']['start'] = $curResult->id;
                    $tracking['l']['count'] = 1;
                }
            }
            else
            {
                if ($tracking['l']['inLine'])
                {
                    $tracking['l']['inLine'] = false;
                    if ($maxLine['l']['count'] < $tracking['l']['count'])
                    {
                        $maxLine['l']['count'] = $tracking['l']['count'];
                        $maxLine['l']['start'] = $tracking['l']['start'];
                    }
                }
            }
        }

        return $maxLine;
    }
}